import React, { useState, memo } from "react"
import { useSelector, useDispatch } from "react-redux"

import { addTodoItem } from "../../store/modules/todo"
import { TextField } from "@mui/material"
import TodoItem from "./TodoItem"

function TodoInput() {
  const dispatch = useDispatch()
  const [content, setContent] = useState("")
  const activeDate = useSelector((state) => state.date.activeDate)
  const handleEnter = (e) => {
    if (e.keyCode === 13 && content) {
      const todoItem = {
        date: activeDate,
        item: {
          content,
          desc: "",
          done: false,
          childTask: [],
          difficulty: 0,
        },
      }
      dispatch(addTodoItem(todoItem))
      setContent("")
    }
  }
  return (
    <div className="px-5 pb-5">
      <TextField
        size="small"
        fullWidth
        label="添加事件"
        placeholder="按回车键创建"
        value={content}
        onChange={(e) => setContent(e.target.value)}
        onKeyUp={(e) => handleEnter(e)}
        autoComplete="off"
      />
    </div>
  )
}

function TodoList() {
  const todoList = useSelector((state) => state.todo.todoList)
  const activeDate = useSelector((state) => state.date.activeDate)
  const todayList = todoList[activeDate.format("YYYY-MM-DD")] || []

  return (
    <div>
      <TodoInput></TodoInput>
      <div>
        {todayList.map((item, index) => {
          return (
            <TodoItem
              key={item.id}
              todoItem={{ ...item, index }}
              activeDate={activeDate}
            />
          )
        })}
      </div>
    </div>
  )
}

export default memo(TodoList)
